using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using SmartLink.EnumLibrary;
using SmartLink.DTOS;

namespace SmartLink.WebApi.Filter
{
    /// <summary>
    /// 参数验证
    /// </summary>
    public class GlobalActionFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (actionContext.ModelState.IsValid != false) return;
            var error = string.Empty;
            foreach (var key in actionContext.ModelState.Keys)
            {
                var state = actionContext.ModelState[key];
                if (!state.Errors.Any()) continue;
                var firstError = state.Errors.First();
                error = firstError.ErrorMessage;
                if (string.IsNullOrWhiteSpace(error))
                    error = firstError.Exception?.Message;
                break;
            }
            actionContext.Response = actionContext.Request.CreateResponse(System.Net.HttpStatusCode.BadRequest, new Results { State = StateCodeEnum.验证报错.GetHashCode(), Message = error });
        }
    }
}